package com.ruoyi.common.s7.ST80;

import com.alibaba.fastjson2.JSON;
import com.github.s7connector.api.DaveArea;
import com.github.s7connector.api.S7Connector;
import com.ruoyi.common.s7.BaseVo;
import com.ruoyi.common.s7.ExchangeIntf;
import com.ruoyi.common.utils.S7StrUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class ST80Exchange implements ExchangeIntf {
    public  static int dataArea = 4410;
    public static String ipAddress = "192.168.0.161";

    /**
     * 读取PLC信息
     * @return
     */
    public ST80Vo readPLC(){
        ST80Handle sT80Handle =   new ST80Handle();
        S7Connector s7Connector = sT80Handle.initConnect(ipAddress);
        ST80Vo st80Vo = sT80Handle.read(s7Connector, dataArea);
        try {
            s7Connector.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return st80Vo;
    }
    /**
     * 将外部订单信息和上游站位检测信息写入PLC
     * @param baseVo
     */
    public void writePLC(BaseVo baseVo){
        ST80Vo st60Vo = (ST80Vo) baseVo;
        ST80Handle sT80Handle =   new ST80Handle();
        S7Connector s7Connector = sT80Handle.initConnect(ipAddress);
        if(st60Vo.getSkipFlag()==2){
            //跳站标记为已跳站
            byte[] data = new byte[1];
            data[0] = st60Vo.getSkipFlag();
            s7Connector.write(DaveArea.DB, dataArea, 177, data);
            return;
        }
        byte[] data = new byte[1];
        data[0] = st60Vo.getModel().byteValue();
        s7Connector.write(DaveArea.DB, dataArea, 51, data);
        sT80Handle.writeValue(s7Connector, dataArea, 52, st60Vo.getModel(), 1);
        sT80Handle.writeValue(s7Connector, dataArea, 54, st60Vo.getManufacturer(), 1);
        sT80Handle.writeValue(s7Connector, dataArea, 56, st60Vo.getDirection(), 1);
        sT80Handle.writeValue(s7Connector, dataArea, 58, st60Vo.getQuntity(), 1);
        byte[] date1 =  S7StrUtils.transform(st60Vo.getDate1(),15);
        s7Connector.write(DaveArea.DB, dataArea, 60, date1);
        byte[] date2 =  S7StrUtils.transform(st60Vo.getDate2(),15);
        s7Connector.write(DaveArea.DB, dataArea, 78, date2);
        byte[] productCode =  S7StrUtils.transform(st60Vo.getDate2(),15);
        s7Connector.write(DaveArea.DB, dataArea, 96, productCode);
        byte[] orderNo =  S7StrUtils.transform(st60Vo.getOrderNo(),15);
        s7Connector.write(DaveArea.DB, dataArea, 114, orderNo);
        try {
            s7Connector.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
